package com.examplemartin.jpademo.controller.admin;

import com.examplemartin.jpademo.bean.AjaxResult;
import com.examplemartin.jpademo.pojo.admin.OperatorLogPO;
import com.examplemartin.jpademo.pojo.po.MenuPO;
import com.examplemartin.jpademo.pojo.po.RolePO;
import com.examplemartin.jpademo.pojo.po.UserPO;
import com.examplemartin.jpademo.pojo.vo.MenuVO;
import com.examplemartin.jpademo.pojo.vo.forauth.RoleVO;
import com.examplemartin.jpademo.service.UserService;
import com.examplemartin.jpademo.service.admin.MenuService;
import com.examplemartin.jpademo.service.admin.OperatorLogService;
import com.examplemartin.jpademo.service.admin.RoleService;
import com.examplemartin.jpademo.util.ValidateMember;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RequestMapping("/role")
@Controller
@Slf4j
public class RoleController {

    @Resource
    private MenuService menuService;
    @Resource
    private RoleService roleService;
    @Resource
    private UserService userService;
    @Resource
    private OperatorLogService operatorLogService;

    /**
     * 跳转到role主页面
     *
     * @return
     */
    @GetMapping("/rolelist.do")
    public String rolelist(Model model) {
        model.addAttribute("title", "角色管理");

        List<RolePO> roleList = roleService.findAll();

        model.addAttribute("roleList", roleList);

        return "role/rolelist";
    }

    /**
     * @return
     */
    @GetMapping("/addrole.do")
    public String addRole(Model model) {
        model.addAttribute("title", "添加角色");
        List<MenuVO> menuList = menuService.getMenuForRole();
        model.addAttribute("menuList", menuList);
        return "role/addrole";
    }

    /**
     * 添加角色 ajax
     *
     * @param rolePO
     *         -- rest对象rolePO
     *
     * @return
     */
    @PostMapping("/addrole.ajax")
    @ResponseBody
    public AjaxResult addRoleAjax(@RequestBody RolePO rolePO, HttpServletRequest request) {

        if (ValidateMember.isEmpty(rolePO)) {
            return AjaxResult.fail(500, "数据上传有误,请联系管理员");
        }

        String name = rolePO.getName();


        // 判断角色名是否重复
        Integer byName = roleService.findByName(name);
        log.info("RoleController.addRolePo.findByName: " + byName);
        if (byName > 0) {
            return AjaxResult.fail(500, "角色已经存在");
        }

        rolePO.setCreateTime(new Date());

        RolePO insertRolePO = roleService.insertRolePO(rolePO);
        log.info("RoleController.addRolePo: " + insertRolePO.getName());


        if (insertRolePO == null) {
            return AjaxResult.fail(500, "新建角色,联系管理员");
        }
        log.info("RoleController.comment: " + rolePO.getComment());

        // 判断 session和loginuserr
        HttpSession session = request.getSession();
        if (ValidateMember.isEmpty(session)) {
            return AjaxResult.fail(500, "有非法操作,请联系管理员");
        }


        UserPO loginuser = (UserPO) session.getAttribute("loginuser");

        if (ValidateMember.isEmpty(loginuser)) {
            return AjaxResult.fail(500, "有非法操作,请联系管理员");
        }

        OperatorLogPO logPO = new OperatorLogPO();
        logPO.setCreateTime(new Date());
        logPO.setContent("创建角色:" + rolePO.getName());

        log.warn("loginuser" + loginuser.toString());

        UserPO userPO = userService.login(loginuser.getLoginname(), loginuser.getPassword());

        logPO.setUser(userPO);

        operatorLogService.saveLog(logPO);

        return AjaxResult.success(200, "成功添加角色", null);

    }

    /**
     * 删除角色 ajax
     *
     * @param rolePO
     *
     * @return
     */
    @PostMapping("/deleterole.ajax")
    @ResponseBody
    public AjaxResult deleteRoleAjax(@RequestBody RolePO rolePO, HttpServletRequest request) {

        if (ValidateMember.isEmpty(rolePO)) {
            return AjaxResult.fail(500, "请选中要删除的角色");
        }
        if (ValidateMember.isEmpty(rolePO.getId())) {
            return AjaxResult.fail(500, "请选中要删除的角色");
        }

        RolePO rolePOById = roleService.findRolePOById(rolePO.getId());
        if (rolePOById == null) {
            return AjaxResult.fail(500, "该角色不存在");
        }

        roleService.deleteRolePo(rolePOById);

        /**
         * 操作日志
         */
        // 判断 session和loginuserr
        HttpSession session = request.getSession();
        if (ValidateMember.isEmpty(session)) {
            return AjaxResult.fail(500, "有非法操作,请联系管理员");
        }


        UserPO loginuser = (UserPO) session.getAttribute("loginuser");

        if (ValidateMember.isEmpty(loginuser)) {
            return AjaxResult.fail(500, "有非法操作,请联系管理员");
        }

        OperatorLogPO logPO = new OperatorLogPO();
        logPO.setCreateTime(new Date());
        logPO.setContent("删除角色:" + rolePOById.getName());

        UserPO userPO = userService.login(loginuser.getLoginname(), loginuser.getPassword());

        logPO.setUser(userPO);

        operatorLogService.saveLog(logPO);

        return AjaxResult.success(200, "角色成功删除", null);
    }

    /**
     * 跳转到修改role主页面
     *
     * @return
     */
    @GetMapping("/editrole.do")
    public String editrole(@RequestParam("id") Long id, Model model) {
        model.addAttribute("title", "角色修改");

        List<MenuVO> menuList = menuService.getMenuForRole();
        model.addAttribute("menuList", menuList);

        List<MenuPO> authorities = roleService.findRolePOById(id).getAuthorities();

        RolePO rolePOById = roleService.findRolePOById(id);
        model.addAttribute("rolepo", rolePOById);


        HashMap<Long, Boolean> ckmap = new HashMap<>();

        for (MenuVO menuVO : menuList) {
            ckmap.put(menuVO.getId(), false);
        }
        for (MenuPO authority : authorities) {
            ckmap.put(authority.getId(), true);
        }
        model.addAttribute("ckmap", ckmap);

        return "role/editrole";
    }

    /**
     * 修改角色
     *
     * @param rolePO
     * @param request
     *
     * @return
     */
    @PostMapping("/saverole.ajax")
    @ResponseBody
    public AjaxResult saveRoleAjax(@RequestBody RoleVO roleVO, HttpServletRequest request) {
        if (ValidateMember.isEmpty(roleVO)) {
            return AjaxResult.fail(500, "数据上传有误,请联系管理员");
        }


/*//        这里用直接保存 ,在有的机器上报错
        // 1. 删除角色
        roleService.deleteRolePo(rolePO);
        // 2. 重新添加角色
        rolePO.setId(null);
        rolePO.setCreateTime(ctime);
        rolePO.setUpdateTime(new Date());
        roleService.insertRolePO(rolePO);*/

        // 获取 oldpo
        RolePO oldpo = roleService.findRolePOById(roleVO.getId());
        // oldpo
        oldpo.setUpdateTime(new Date());
        oldpo.setUrl(roleVO.getUrl());
        oldpo.setStatus(roleVO.getStatus());
        oldpo.setIcon(roleVO.getIcon());
        oldpo.setName(roleVO.getName());
        oldpo.setComment(roleVO.getComment());

        // 更新基础信息
        oldpo = roleService.save(oldpo);

        // 更新关联menu --01 删除老条目
//        for (MenuPO authority : oldpo.getAuthorities()) {
//            oldpo.getAuthorities().remove(authority);
//
//        }
        oldpo.setAuthorities(new ArrayList<MenuPO>());
        oldpo = roleService.save(oldpo);

        // 添加新条目
        for (com.examplemartin.jpademo.pojo.vo.forauth.ForAuthMenuVO authority : roleVO.getAuthorities()) {
            MenuPO menuById = menuService.getMenuById(authority.getId());
            oldpo.getAuthorities().add(menuById);

        }
        oldpo = roleService.save(oldpo);

        /**
         * 操作日志
         *//*
        // 判断 session和loginuserr
        HttpSession session = request.getSession();
        if (ValidateMember.isEmpty(session)) {
            return AjaxResult.fail(500, "有非法操作,请联系管理员");
        }


        UserPO loginuser = (UserPO) session.getAttribute("loginuser");

        if (ValidateMember.isEmpty(loginuser)) {
            return AjaxResult.fail(500, "有非法操作,请联系管理员");
        }

        OperatorLogPO logPO = new OperatorLogPO();
        logPO.setCreateTime(new Date());
        logPO.setContent("修改角色:" + oldpo.getName());


        UserPO userPO = userService.login(loginuser.getLoginname(), loginuser.getPassword());

        logPO.setUser(userPO);

        operatorLogService.saveLog(logPO);*/


        return AjaxResult.success(200, "成功修改角色:" + oldpo.getName(), null);

    }

    @GetMapping("/searchrole.do")
    public String searchRoleListDo(@RequestParam(value = "name", required = false) String name, Model model) {
        List<RolePO> roleList = null;
        if (ValidateMember.isEmpty(name)) {
            roleList = roleService.findAll();

            model.addAttribute("roleList", roleList);
        } else {
            roleList = roleService.findAllByNameLike(name);
            model.addAttribute("roleList", roleList);
        }

        log.warn("searchRoleListDo:" + name);
        return "role/rolelist";
    }

}
